package com.example.viewpagertest.activity

import android.os.Bundle
import android.util.DisplayMetrics
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import com.example.viewpagertest.adapter.ViewPagerAdapter
import com.example.viewpagertest.fragment.FirstFragment
import com.example.viewpagertest.fragment.SecondFragment

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //FrameLayout 作为根视图
        val rootView = FrameLayout(this)
        rootView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        setContentView(rootView)



        // 调用函数来创建并添加 ViewPager2
        addViewPager(rootView)
    }

    // 修改函数，接收一个父布局作为参数
    private fun addViewPager(parentView: ViewGroup) {
        val viewPager = ViewPager2(this).apply {
            // 设置布局参数，使其充满父布局
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )

            // 设置适配器
            adapter = ViewPagerAdapter(fragmentManager = supportFragmentManager, lifecycle = lifecycle).apply {
                addFragment(FirstFragment())
                addFragment(SecondFragment())
                addFragment(FirstFragment())
                addFragment(SecondFragment())
                addFragment(FirstFragment())
                addFragment(SecondFragment())
                addFragment(FirstFragment())
                addFragment(SecondFragment())

            }
        }

        // 关键步骤：将创建的 ViewPager2 添加到父布局中
        parentView.addView(viewPager)
    }
}